local width = 640
local height = 640

local unitSize = 20

local initX = 320
local initY = 320

local dir = 1

local snakes = {}

-- 食物状态
-- WaieToTat 绘制食物
-- BeEated 随机生成食物
local foodState = "WaitToEat"

-- 游戏状态
-- 0 游戏结束
-- 1 游戏正常
local gameState = 1

-- 食物的位置
local foodX = 0
local foodY = 0

function love.load()
	love.window.setTitle("Love2D-贪吃蛇-aka")

	love.window.setMode(width,height)

	myFont = love.graphics.newFont(30)

	love.graphics.setFont(myFont)

	love.graphics.setBackgroundColor(255,255,255,255)

	love.graphics.setLineStyle("smooth")

	love.graphics.setLineWidth(0.1)

	for i = 1,5 do
		snake = {}

		snake.x = initX + (i-1) * 20

		snake.y=initY

    	snakes[i]=snake
    end
  	foodX=love.math.random(32-1)*20

  	foodY=love.math.random(32-1)*20
end

function love.draw()
  love.graphics.setColor(0,0,0,255)

  for i = 0,width,unitSize do
    love.graphics.line(0,i,height,i)
  end

  for j=0,height,unitSize do
    love.graphics.line(j,0,j,width)
  end

  for i=1,table.maxn(snakes) do
    love.graphics.setColor(0,0,255,255)
    love.graphics.rectangle("fill",snakes[i].x,snakes[i].y,20,20)
  end

  if(foodState=="WaitToEat") then
    love.graphics.setColor(255,0,0,255)
    love.graphics.rectangle("fill",foodX,foodY,20,20)
  end

  if(gameState==0) then
    love.graphics.setColor(255,0,0,255)
    love.graphics.print("Game Over",250,300)
  end
end

function love.update(dt)
  if(snakes[1].x<=0 or snakes[1].x>=640 or snakes[1].y<=0 or snakes[1].y>=640) then
    gameState=0
  else
    gameState=1
  end

  if(gameState==1) then
    SnakeUpdate()
    FoodUpdate()
  end
end

function SnakeUpdate()
  local n=table.maxn(snakes)
  if(table.maxn(snakes)>0) then
    if(getNextPoint().x==foodX and getNextPoint().y==foodY) then
      table.insert(snakes, 1, getNextPoint())
      foodState="BeEated"
    else
      table.insert(snakes, 1, getNextPoint())
      table.remove(snakes,n+1)
    end 
  end
end

function FoodUpdate()
  if(foodState=="BeEated") then
    foodX=love.math.random(32-1)*20
    foodY=love.math.random(32-1)*20
    foodState="WaitToEat"
   end
end

function love.keypressed(key)
  if(key=="a" and dir~=3) then 
    dir=2
  end
  if(key=="d" and dir~=2) then 
    dir=3
  end
  if(key=="w" and dir~=1) then 
    dir=0
  end
  if(key=="s" and dir~=0) then 
    dir=1
  end
end

function getNextPoint()
  snake={}
  if(dir==0) then
    snake.x=snakes[1].x
    snake.y=snakes[1].y-20
  end
  if(dir==1) then
    snake.x=snakes[1].x
    snake.y=snakes[1].y+20
  end
  if(dir==2) then
    snake.x=snakes[1].x-20
    snake.y=snakes[1].y
  end
  if(dir==3) then
    snake.x=snakes[1].x+20
    snake.y=snakes[1].y
  end

  return snake
end